package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.mappers.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    @Override
    public R<Employee> login(Employee employee) {
        //查询到的员工
        Employee dbEmployee = employeeMapper.login(employee.getUsername());

        //验证账号是否存在
        if (dbEmployee==null) {
            return R.error("用户名不存在");
        }

        //用户输入的密码转换为md5
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        //密码比对
        if (!dbEmployee.getPassword().equals(password)) {
            return R.error("密码错误");
        }

        // 查询状态码
        if (dbEmployee.getStatus() == 0) {
            return R.error("账户被禁用");
        }

         return R.success(dbEmployee);
    }

    @Override
    public void save(Employee employee) {
        employee.setPassword(DigestUtils.md5DigestAsHex("123".getBytes()));
        employee.setStatus(1);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        employeeMapper.save(employee);
    }

    @Override
    public R<Page<Employee>> findByPage(Integer page, Integer pageSize, String name) {
        //1. 设置当前页与页面大小
        PageHelper.startPage(page,pageSize);

        //2. 查询数据
        List<Employee> employeeList = employeeMapper.findByPage(name);

        //3. 创建PageINfo对象，把list集合传入
        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);

        //4. 把pageInfo的信息转移到Page对象
        Page<Employee> pageResult = new Page<>(pageInfo.getList(),pageInfo.getTotal(),page,pageSize);

        return R.success(pageResult);
    }

    @Override
    public void update(Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());

        employeeMapper.update(employee);
    }

    @Override
    public R<Employee> findById(Long id) {
        Employee employee = employeeMapper.findById(id);
        return R.success(employee);
    }
}
